package instrarbre;

import exprarbre.ASAExpr;
import java.util.HashMap;
import java.util.LinkedList;
import javax.swing.JTextArea;

public class ASASwitch extends ASAInstr {

    private ASAExpr expression;
    private LinkedList<ASACase> instructions;

    public ASASwitch(ASAExpr expression) {
        this.expression = expression;
        this.instructions = new LinkedList<ASACase>();
    }

    public void add(ASACase instruction) {
        semantique(instruction);
        this.instructions.add(instruction);
    }

    private void semantique(ASACase instruction) {
        for (ASACase caseInstr : instructions) {
            if (caseInstr.isCorresponding(instruction.getCaseValue())) {
                throw new RuntimeException("Case de même valeur : " + instruction.getCaseValue());
            }
        }
    }

    @Override
    protected String notationExplorateur(String prefixe) {
        String res = super.notationExplorateur(prefixe);
        String prefixeSuiv = prefixe + "  ";
        for (ASAInstr instruction : instructions) {
            res += instruction.notationExplorateur(prefixeSuiv);
        }
        return res;
    }

    @Override
    public void interpreter(HashMap<String, Integer> affectation) {
        boolean isJump = false;
        for (ASACase instruction : instructions) {
            if (instruction.isCorresponding(expression.evalue(affectation)) || isJump) {
                isJump = true;
                try {
                    instruction.interpreter(affectation);
                }
                catch (BreakException e) {
                    break;
                }
            }
        }
    }

    @Override
    public void setView(JTextArea area) {
        for (ASAInstr instruction : instructions) {
            instruction.setView(area);
        }
    }
}